/*******************************************************************************
 * Copyright (c) 2010, 2030 www.itlaobing.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.itlaobing.shopping.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itlaobing.annotation.RequestMapping;


/** 
 * ClassName: BaseServlet <br/> 
 * Function: TODO 功能描述 <br/> 
 * date: 2017年11月1日 <br/> 
 * 
 * @author 王建蕊 
 * @version 1.0 
 * @since JDK 1.8 
 */
public class BaseServlet extends HttpServlet{
	
	/**
	 * 保存URL 与method之间的映射关系
	 */
	private Map<String,Method> requestMappings=new HashMap<>();
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到当前请求的url
		String requestUrl=req.getRequestURI();
		//从map中取得方法
		Method method=requestMappings.get(requestUrl);
		if(method==null) {
			resp.sendError(404,"请求路径发生错误");
			return;
		}
		//调用方法
		try {
			method.invoke(this, req,resp);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		//取得当前servlet的类
		Class clz=this.getClass();
		//取得webservlet的对象
		WebServlet webservlet=(WebServlet)clz.getAnnotation(WebServlet.class);
		//获取基础的URL
		String baseUrl=webservlet.value()[0];
		//反射取得所有的方法
		Method[] methods=clz.getDeclaredMethods();
		for(Method method:methods) {
			//查看方法上是否标注了requestmapping
			if(method.isAnnotationPresent(RequestMapping.class)) {
				RequestMapping requestmapping=method.getAnnotation(RequestMapping.class);
				//获取url
				String url=requestmapping.value();
				if(!url.startsWith("/")) {
					url="/"+url;
				}
				String fullUrl=baseUrl.replace("/*", "")+url;
				requestMappings.put(fullUrl, method);
			}
		}
		
		
	}
	
}
